//   
//   HomeViewController.swift
//   BaseComponetKit
//   Created  by monkey on 2024/4/2
//   
//   
   

import UIKit

class HomeViewController: UIViewController,MenuViewDelegate {
    
    private var timeLineData: [(title: String, detail: String, time: String)] = []
    
    private let tabBarHeight: CGFloat = 49 // Assuming default tab bar height
    
    
    private let tableView: UITableView = {
        let tableView = UITableView(frame: .zero, style: .plain)
        tableView.register(TimeLineCell.self, forCellReuseIdentifier: "TimeLineCell")
        return tableView
    }()
    
    private lazy var carouselView: CarouselView = {
        let carouselView = CarouselView(frame: .zero, images: [])
        carouselView.didSelectItem { index in
            print("Clicked index: \(String(describing: index))")
        }
        return carouselView
    }()
    
    
    private lazy var menuView: MenuView = {
        let menuView = MenuView(frame: CGRect(x: 0, y: 200, width: view.frame.width, height: 250))
     
        return menuView
    }()
    
    
    func menuView(_ menuView: MenuView, didSelectItemAt index: Int, item: MenuItem) {
        print("Selected menu item: \(item.rawValue)")
        switch item {
        case .stool:
            // 执行特定于 "stool" 菜单项的操作
            print("Special operation for stool menu item")
        default:
            // 对于其他菜单项，暂时不执行任何操作
            break
        }
    }


    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 添加轮播图
        // 加载本地资源图片
        var images : [UIImage] = []
        
        if let image1 = UIImage(named: "app-banner1"),
           let image2 = UIImage(named: "app-banner2"),
           let image3 = UIImage(named: "app-banner3") {
            // 将图片添加到 images 数组中
            images.append(image1)
            images.append(image2)
            images.append(image3)
        }
        
//        carouselView = CarouselView(frame: CGRectZero, images: [])
//        carouselView.didSelectItem { index in
//            print("Clicked index: \(String(describing: index))")
//
//        }
   
        view.addSubview(carouselView)
       
        DispatchQueue.main.asyncAfter(deadline: .now() + 5) { [weak self] in
            self?.carouselView.updateImage(images)
        }
        carouselView.snp.makeConstraints { make in
                  make.top.equalToSuperview().offset(0) // Adjust top constraint as needed
                  make.leading.equalToSuperview()
                  make.trailing.equalToSuperview()
                  make.height.equalTo(200) // Adjust height as needed
              }
        
        // 添加菜单
//        let menuView = MenuView(frame: CGRect(x: 0, y: 200, width: view.frame.width, height: 250))
        menuView.delegate = self
        view.addSubview(menuView)
        menuView.backgroundColor = .white
//        carouselView.currentPageDidChange = { index in
//            menuView.backgroundColor =  images[index].averageColorInCenter()?.withAlphaComponent(0.9)
//            
//        }
        carouselView.currentPageDidChange = { [weak self] index in
            guard let self = self else { return }
            guard index >= 0 && index < images.count else { return } // 确保索引在合理范围内

            UIView.animate(withDuration: 0.5) { [self] in
                let startColor = images[index].averageColorInCenter()?.withAlphaComponent(0.0) ?? UIColor.clear
                let endColor = images[index].averageColorInCenter()?.withAlphaComponent(0.9) ?? UIColor.clear
                
                let gradientLayer = CAGradientLayer()
                gradientLayer.colors = [startColor.cgColor, endColor.cgColor]
                gradientLayer.locations = [0.0, 1.0]
                gradientLayer.startPoint = CGPoint(x: 0.0, y: 0.0)
                gradientLayer.endPoint = CGPoint(x:1.0, y: 1.0)
                gradientLayer.frame = self.menuView.bounds
                self.menuView.layer.insertSublayer(gradientLayer, at: 0)
            }
        }


        
        // 添加列表视图
//        let tableView = UITableView(frame: CGRect(x: 0, y: 450, width: view.frame.width, height: view.frame.height - 300))
//        tableView.dataSource = self
//        tableView.delegate = self
//        view.addSubview(tableView)
        setupTableView()
        generateTimeLineData()
        
    }
}

extension HomeViewController: UITableViewDataSource, UITableViewDelegate {
    
    private func generateTimeLineData() {
        for i in 1...20 {
            let title = "Title \(i)"
            let detail = "Detail for item \(i)"
            let time = "Time \(i)"
            let data = (title: title, detail: detail, time: time)
            timeLineData.append(data)
        }
        tableView.reloadData()
    }
    private func setupCarouselView() {
         view.addSubview(carouselView)
         carouselView.snp.makeConstraints { make in
             make.top.equalToSuperview().offset(0) // Adjust top constraint as needed
             make.leading.trailing.equalToSuperview()
             make.height.equalTo(200) // Adjust height as needed
         }
     }
    
    // MARK: - UITableViewDataSource
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return timeLineData.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "TimeLineCell", for: indexPath) as! TimeLineCell
        let data = timeLineData[indexPath.row]
        cell.configure(title: data.title, detail: data.detail, time: data.time)
        return cell
    }
    
    // MARK: - UITableViewDelegate
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 120 // Set your desired height here
    }
    
    // MARK: - Private Methods
    
    private func setupTableView() {
        view.addSubview(tableView)
        tableView.delegate = self
        tableView.dataSource = self
        tableView.snp.makeConstraints { make in
            make.top.equalTo(menuView.snp.bottom).offset(10)
            make.leading.trailing.equalToSuperview()
            make.bottom.equalTo(view.safeAreaLayoutGuide.snp.bottom).offset(-10)
        }
    }
}

